package com.ryl.yomall.activity.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ryl.yomall.activity.mapper.SeckillGoodsMapper;
import com.ryl.yomall.activity.service.SecKillGoodsService;
import com.ryl.yomall.activity.util.CacheHelper;
import com.ryl.yomall.activity.util.DateUtil;
import com.ryl.yomall.model.activity.SeckillGoods;
import com.ryl.yomall.model.activity.UserRecode;
import com.ryl.yomall.model.common.constant.RedisConst;
import com.ryl.yomall.model.common.result.Result;
import com.ryl.yomall.model.common.result.ResultCodeEnum;
import com.ryl.yomall.model.common.util.AuthContextHolder;
import com.ryl.yomall.model.common.util.MD5;
import com.ryl.yomall.model.list.Goods;
import com.ryl.yomall.model.order.OrderDetail;
import com.ryl.yomall.model.order.OrderInfo;
import com.ryl.yomall.model.user.UserAddress;
import com.ryl.yomall.order.client.OrderFeignClient;
import com.ryl.yomall.rabbitmq.constant.MQConstant;
import com.ryl.yomall.rabbitmq.service.RabbitService;
import com.ryl.yomall.user.client.UserFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @Date 19:42
 * @Author ryl
 */
@RestController
@RequestMapping("/api/activity")
public class SecKillApiController {
    @Autowired
    private SecKillGoodsService secKillGoodsService;
    @Autowired
    private RabbitService rabbitService;
    @Autowired
    private UserFeignClient userFeignClient;
    @Autowired
    private OrderFeignClient orderFeignClient;

    //盐值
    private String salt = "qwertyuiop";
    @GetMapping("/list")
    public List<SeckillGoods> list(){
        List<SeckillGoods> list=secKillGoodsService.list();
        return list;
    }
    @GetMapping("/getSeckillGoods/{skuId}")
    public SeckillGoods getSeckillGoods(@PathVariable Long skuId){
        return secKillGoodsService.getSeckillGoods(skuId);
    }
    //获取抢购码
    @GetMapping("/seckill/auth/getSeckillSkuIdStr/{skuId}")
    public Result getSeckillSkuIdStr(@PathVariable Long skuId, HttpServletRequest request) {
        SeckillGoods seckillGoods = secKillGoodsService.getSeckillGoods(skuId);
//        1、要求商品必须在活动时间内
        Date startTime = seckillGoods.getStartTime();
        Date endTime = seckillGoods.getEndTime();
        Calendar instance = Calendar.getInstance();
        Date curTime = instance.getTime();

        //startTime <= curTime <= endTime 活动时间内  前面>后面=false  == 前面<=后面=true
        // startTime > curTime
        if (!DateUtil.dateCompare(startTime, curTime)) {
            return Result.build(null, ResultCodeEnum.SECKILL_NO_START);
        }
        //endTime <= curTime  活动结束了
        if (DateUtil.dateCompare(endTime, curTime)) {
            return Result.build(null, ResultCodeEnum.SECKILL_END);
        }
//        2、库存
        if (seckillGoods.getStockCount() <= 0) {
            return Result.build(null, ResultCodeEnum.SECKILL_FINISH);
        }
//        3、审核通过
        if (!seckillGoods.getStatus().equals("1")) {//硬编码问题
            return Result.build(null, ResultCodeEnum.SECKILL_ILLEGAL);
        }
//        4、获取到抢购码
        String userId = AuthContextHolder.getUserId(request);
        String encrypt = MD5.encrypt(userId + skuId + salt);
//        5、Md5（userId+skuId+...)
//        6、好处：不用保存抢购码
        return Result.ok(encrypt);
    }
    //开始秒杀
    @PostMapping("/seckill/auth/seckillOrder/{skuId}")
    public Result seckillOrder(@PathVariable Long skuId, String skuIdStr, HttpServletRequest request) {
        String userId = AuthContextHolder.getUserId(request);
//        1、校验抢购码
        String encrypt = MD5.encrypt(userId + skuId + salt);
        if (!encrypt.equals(skuIdStr)) {
            return Result.build(null, ResultCodeEnum.SECKILL_ILLEGAL);
        }
//        2、状态位 skuId:0
//        本地内存
        String state = (String) CacheHelper.get(skuId.toString());
        if (!"1".equals(state)) {
            return Result.build(null, ResultCodeEnum.SECKILL_FINISH);
        }
//        3、发消息  skuId userId
        UserRecode userRecode = new UserRecode();
        userRecode.setUserId(userId);
        userRecode.setSkuId(skuId);
        //发消息
        rabbitService.sendMessage( MQConstant.EXCHANGE_DIRECT_SECKILL_USER,
                MQConstant.ROUTING_SECKILL_USER, userRecode);
//        4.Result.oK
        return Result.ok();
    }
    //查询结果
    @GetMapping("/seckill/auth/checkOrder/{skuId}")
    public Result checkOrder(@PathVariable Long skuId, HttpServletRequest request) {
        String userId = AuthContextHolder.getUserId(request);
        //3:用户是否已经来过了
        Object o2 = redisTemplate.opsForValue().get(RedisConst.SECKILL_USER +
                userId + ":" + skuId);
        if (null != o2) {
            //1:查询是否已经下单了
            Object o = redisTemplate.opsForValue().get(RedisConst.SECKILL_ORDERS_USERS + userId);
            if (null != o) {
                return Result.build(null, ResultCodeEnum.SECKILL_ORDER_SUCCESS);
            }
            //2:查询是否有抢购资格
            Object o1 = redisTemplate.opsForValue().get(RedisConst.SECKILL_ORDERS + userId);
            if (null != o1) {
                return Result.build(null, ResultCodeEnum.SECKILL_SUCCESS);
            }
        }
        //4:状态位
        Object o3 = CacheHelper.get(skuId.toString());
        if (!"1".equals(o3)) {
            return Result.build(null, ResultCodeEnum.SECKILL_FAIL);
        }
        //排队中
        return Result.build(null, ResultCodeEnum.SECKILL_RUN);
    }

    //下单
    @GetMapping("/seckill/auth/trade")
    public Result trade(HttpServletRequest request){

        String userId = AuthContextHolder.getUserId(request);

        List<UserAddress> userAddressList = userFeignClient.findUserAddressListByUserId(userId);

        String skuId= (String) redisTemplate.opsForValue ( ).get ( RedisConst.SECKILL_ORDERS
                + userId );
        QueryWrapper<SeckillGoods> queryWrapper=new QueryWrapper<> (  );
        queryWrapper.eq ( "sku_id",skuId );
        SeckillGoods seckillGoods =seckillGoodsMapper.selectOne ( queryWrapper );
        // 声明一个集合来存储订单明细
        ArrayList<OrderDetail> detailArrayList = new ArrayList<>();
        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setSkuId(seckillGoods.getSkuId());
        orderDetail.setSkuName(seckillGoods.getSkuName());
        orderDetail.setImgUrl(seckillGoods.getSkuDefaultImg());
        orderDetail.setSkuNum(1);
        orderDetail.setOrderPrice(seckillGoods.getCostPrice());
        // 添加到集合
        detailArrayList.add(orderDetail);

        Map<String, Object> result = new HashMap<> ();
        result.put("userAddressList", userAddressList);
        result.put("detailArrayList", detailArrayList);
        // 保存总金额
        result.put("totalAmount", orderDetail.getOrderPrice());
        result.put("totalNum", orderDetail.getSkuNum());
        return Result.ok(result);
    }


    /**
     * 秒杀提交订单
     *
     * @param orderInfo
     * @return
     */
    @PostMapping("auth/submitOrder")
    public Result submitOrder(@RequestBody OrderInfo orderInfo,HttpServletRequest request) {
        String userId = AuthContextHolder.getUserId(request);

        Object o = redisTemplate.boundHashOps ( RedisConst.SECKILL_ORDERS ).get ( userId );
        if (null == o) {
            return Result.fail().message("非法操作");
        }

        orderInfo.setUserId(Long.parseLong(userId));

        Long orderId = orderFeignClient.submitOrder(orderInfo);
        if (null == orderId) {
            return Result.fail().message("下单失败，请重新操作");
        }

        //删除下单信息
        redisTemplate.boundHashOps(RedisConst.SECKILL_ORDERS).delete(userId);
        //下单记录
        redisTemplate.boundHashOps(RedisConst.SECKILL_ORDERS_USERS).put(userId, orderId.toString());

        return Result.ok(orderId);
    }



    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private SeckillGoodsMapper seckillGoodsMapper;
}
